package com.dp.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dp.blog.domain.po.Blog;
import com.dp.blog.mapper.BlogMapper;
import com.dp.blog.service.IBlogService;
import com.dp.common.constants.SystemConstants;
import com.dp.common.domain.dto.Result;
import com.dp.common.domain.dto.UserDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dp.common.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.dp.common.constants.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

/*
    @Resource
    private IUserService userService;
*/
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(this::userByBlog);
        // 3. 查询blog是否被点赞
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        // 1. 查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("博客不存在！");
        }
        // 2. 查询blog作着
        userByBlog(blog);
//        isBlogLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result likeBlog(Long id) {
        Long userId = UserHolder.getUser().getId();
        // 2. 判断当前登录用户是否点赞
        String key = BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet()
                .score(key, userId.toString());
        if (score == null) {
            // 3. 如果未点赞
            // 3.1 数据库点赞数+1
            boolean isSuccess = update().setSql("liked = liked + 1")
                    .eq("id", id)
                    .update();
            // 3.2 将当前用户存入RedisZSet集合 zadd key value score
            if (isSuccess) {
                stringRedisTemplate.opsForZSet()
                        .add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            // 4. 如果点赞
            // 4.1 数据库点赞数-1
            boolean isSuccess = update().setSql("liked = liked - 1")
                    .eq("id", id)
                    .update();
            // 4.2 将当前用户从RedisSet集合移除
            if (isSuccess) {
                stringRedisTemplate.opsForZSet()
                        .remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        // 1. 查询top5的点赞用户 zrange key 0 4
        String key = BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet()
                .range(key, 0, 4);
        // 2. 解析出用户id
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5.stream()
                .map(Long::valueOf)
                .collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
/* TODO       // 3. 根据id查询用户
        List<User> users = userService.query()
                .in("id", ids)
                .last("ORDER BY FIELD(id,"+idStr+")")
                .list();
        List<UserDTO> UserDTOS = users.stream()
                .map(user ->
                        BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 4. 返回
        return Result.ok(UserDTOS);*/
        return null;
    }

    private void userByBlog(Blog blog) {
        Long userId = blog.getUserId();
/* TODO        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());*/
        // 查询blog是否被点赞
        isBlogLiked(blog);
    }

    private void isBlogLiked(Blog blog) {
        // 1. 获取当前登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 用户未登录，不需要查询是否点赞
            return;
        }
        Long userId = UserHolder.getUser().getId();
        // 2. 判断当前登录用户是否点赞
        String key = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet()
                .score(key, userId.toString());
        blog.setIsLike(score != null);
    }
}
